package com.cw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.api.Response;
import com.cw.constant.Constants;
import com.cw.dto.RjszDTO;
import com.cw.entity.*;
import com.cw.mapper2.*;
import com.cw.service.IPatientBedMiddleRjszService;
import com.cw.util.HttpUtil;
import com.cw.util.MQMsg;
import com.cw.util.UUIDUtil;
import com.cw.vo.ResultRjszVO;
import com.cw.vo.ThisIiPrepayinRJVO;
import com.cw.vo.rjszVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author smq
 * @since 2021-05-09
 */
@Service
@Transactional(rollbackFor = Exception.class, timeout = 5)
public class PatientBedMiddleRjszServiceImpl extends ServiceImpl<PatientBedMiddleRjszMapper, PatientBedMiddleRjbf> implements IPatientBedMiddleRjszService {

    @Autowired
    private ThisIiPrepayinMapper thisIiPrepayinMapper;

    @Autowired
    private WeChatLogMapper weChatLogMapper;

    @Autowired
    private TelMessageMapper telMessageMapper;

    @Autowired
    private MqLogMapper mqLogMapper;

    @Autowired
    private REmployeeMapper rEmployeeMapper;

    @Autowired
    private PatientBedMiddleRjszMapper patientBedMiddleRjszMapper;

    private MQMsg mqMsg = new MQMsg();

    private static ReentrantLock lock = new ReentrantLock();


    @Override
    public ThisIiPrepayinRJVO getIiPrepayinByIdRJ(BigDecimal preid) {
        return baseMapper.getIiPrepayinByIdRJ(preid);
    }

    @Override
    public ResultRjszVO searchRJSS() {
        ResultRjszVO resultRjszVO = new ResultRjszVO();
        List<rjszVO> rjszVOS = baseMapper.searchRJSS();
        resultRjszVO.setRjszVOS(rjszVOS);
        resultRjszVO.setTimeSlotNum(baseMapper.searchCount(1));
        return resultRjszVO;
    }

    @Override
    public ResultRjszVO searchRJSZ() {
        ResultRjszVO resultRjszVO = new ResultRjszVO();
        List<rjszVO> rjszVOS = baseMapper.searchRJSZ();
        List<rjszVO> rjszVOSList = rjszVOS.stream().sorted(Comparator.comparing(rjszVO::getSzrq, Comparator.naturalOrder())
                .thenComparing(rjszVO-> Integer.parseInt(rjszVO.getTimeSlot().substring(0,rjszVO.getTimeSlot().indexOf(":"))), Comparator.naturalOrder())).collect(Collectors.toList());
        resultRjszVO.setRjszVOS(rjszVOSList);
        resultRjszVO.setTimeSlotNum(baseMapper.searchCount(4));
        return resultRjszVO;
    }


    /**
     * 日间输注预约
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response addPatientBed(RjszDTO entity){

        lock.lock();
        ThisIiPrepayin thisIiPrepayin;
        try {
            thisIiPrepayin = thisIiPrepayinMapper.selectById(entity.getPreid());
            if (!("2739").equals(thisIiPrepayin.getNurseCellCode())){
                return new Response(500, "预约失败，该患者不归属于二十一病区");
            }
            //判断是否被预约
            List<PatientBedMiddleRjbf> patientBedNew = baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddleRjbf())
                    .eq(PatientBedMiddleRjbf::getPreid,entity.getPreid())
                    .eq(PatientBedMiddleRjbf::getState, "1")
                    .eq(PatientBedMiddleRjbf::getType,entity.getBedType()));
            if (CollectionUtils.isNotEmpty(patientBedNew)) {
                return new Response(500, "预约失败,该患者已预约日间手术/日间输注");
            }
            //判断预约患者者是否 0取消预约2转入院3出院9作废
            //获取患者信息
            if ("0".equals(thisIiPrepayin.getPreState())) {
                return new Response(500, "预约失败，该患者电子住院证已取消");
            }
            else if ("1".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "预约失败，该患者已预约床位");
            }
            else if ("2".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "预约失败，该患者已入院");
            }
            else if ("3".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "预约失败，该患者已出院");
            }
            else if ("9".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "预约失败，该患者电子住院证已作废");
            }
            else {

            }

//            //根据病人PreId获取病人信息
//            ThisIiPrepayin patientInfo = thisIiPrepayinMapper.selectById(entity.getPreid());
            //根据病人PreId获取电子一体化床位申请信息
            PatientBedMiddleRjbf patientBed = new PatientBedMiddleRjbf();
            patientBed.setId(UUIDUtil.uuid());
            patientBed.setPreid(thisIiPrepayin.getPreid());
            patientBed.setYard("1");
            patientBed.setNurseCellCode("2739");
            patientBed.setNurseCellName("二十一病区");
            patientBed.setDeptCode("1664");
            patientBed.setDeptName("日间治疗中心");
            //已预约
            patientBed.setState("1");
            patientBed.setOperCode(entity.getJobnumber());
            patientBed.setOpenName(entity.getCreateBy());
            patientBed.setOperTime(LocalDateTime.now());
            patientBed.setAppointmentTime(entity.getAppoinmentTime());
            patientBed.setType(entity.getBedType());
            patientBed.setAppointmentClasses(entity.getAppointmentClasses());
            patientBed.setDocCode(entity.getDocCode());
            patientBed.setDocName(entity.getDocName());
            //如果电子住院证中有住院号,将住院号回写至预约表(先去住院处登记的情况)
            patientBed.setInpatientNo(thisIiPrepayin.getInpatientNo());
            patientBed.setCreateTime(new Date());
            baseMapper.insert(patientBed);
        } catch (Exception e) {
            return new Response(500, "预约失败");
        } finally {
            lock.unlock();
        }

        return new Response(200, "预约成功");

    }
    /**
     * 取消预约
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response delPatientBed(String id) {
        try {

            //根据床位id和患者id获取中间表信息
            PatientBedMiddleRjbf info = baseMapper.selectById(id);
            if (info==null) {
                return new Response(500, "取消失败，该患者没有预约记录");
            }
            //修改状态
            info.setState("0");
            info.setOpenName(HttpUtil.getRequestHeaderInfo(Constants.USER_NAME)+"取消预约");
            info.setOperTime(LocalDateTime.now());
            Integer del = baseMapper.updateById(info);

        } catch (Exception ex) {
            int a =0;
        }
        return new Response(200, "取消成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updatePatientBed(String id) {
        try {

            //根据床位id和患者id获取中间表信息
            PatientBedMiddleRjbf info = baseMapper.selectById(id);
            if (info==null) {
                return new Response(500, "输注失败，该患者没有预约记录");
            }
            //修改状态
            info.setState("2");
            Integer update = baseMapper.updateById(info);

        } catch (Exception ex) {
            int a =0;
        }
        return new Response(200, "输注完成");
    }

}
